import { Text, Flex, Image, Button, Spinner, Icon } from '@chakra-ui/react';
import { useContext, useEffect, useState } from 'react';
import { ImageUploaderTriggerContext } from '../ImageUploader/ImageUploaderTriggerContext';
import getPixels, { handlePixels } from '../util/getPixels';
import { getLayerImage } from '../util/getLayerImage';
import { ScrollArea } from '@mantine/core';
import DiffLevelSlider from './DiffLevelSlider';
import LayerCountSlide from './LayerCountSlide';
import { useStore } from '@nanostores/react';
import {
  $diffLevel,
  $layerCount,
  $layerSrcList,
  LayerImage,
  $hideIndex,
} from '../store';
import { FaEyeSlash, FaEye } from 'react-icons/fa';
export default function LayerBox() {
  const { file } = useContext(ImageUploaderTriggerContext);
  const [loading, setLoading] = useState<boolean>(false);
  const diffLevel = useStore($diffLevel);
  const hideIndex = useStore($hideIndex);
  const layerCount = useStore($layerCount);
  const layerSrcList = useStore($layerSrcList);

  const handleSeparate = () => {
    if (layerSrcList) {
      layerSrcList.forEach(({ src }) => {
        URL.revokeObjectURL(src);
      });
    }
    if (!file) {
      setLoading(false);
      return;
    }
    getPixels(file.preview).then((_pixels) => {
      // setPixels(_pixels);
      const [width, height] = _pixels.shape;
      const { colorPixelsMap, mostColorsList } = handlePixels(
        _pixels,
        diffLevel,
        layerCount
      );
      const _layerSrcList: LayerImage[] = [];
      const _hideIndex: boolean[] = [];
      mostColorsList.forEach((color: string) => {
        const lSrc = getLayerImage(
          width,
          height,
          color,
          colorPixelsMap[color].pixels,
          _pixels.stride
        );
        if (lSrc) {
          _layerSrcList.push({ src: lSrc, color });
          _hideIndex.push(true);
        }
      });
      $layerSrcList.set(_layerSrcList);
      $hideIndex.set(_hideIndex);
      setLoading(false);
    });
  };

  const handleHideLayer = (index: number) => {
    const newHideList = hideIndex.slice();
    newHideList[index] = !newHideList[index];
    $hideIndex.set(newHideList);
  };

  useEffect(() => {
    $layerSrcList.set([]);
    $hideIndex.set([]);
  }, [file]);

  return file ? (
    <Flex
      h="full"
      w="340px"
      padding="2"
      rounded="md"
      bg="blackAlpha.200"
      _dark={{
        bg: 'whiteAlpha.200',
      }}
      flexDirection="column"
    >
      <Flex flexDirection="column" gap="2" mb="2">
        <DiffLevelSlider />
        <LayerCountSlide />
        <Flex p="2" justify="center" h="16" align="center">
          <Button
            isLoading={loading}
            rounded="full"
            onClick={() => {
              setLoading(true);
              handleSeparate();
            }}
          >
            分 色
          </Button>
        </Flex>
      </Flex>
      <Flex>
        {loading ? (
          <Flex p="2" justify="center" w="full" h="20rem" align="center">
            <Spinner size="md" color="gray.100" />
          </Flex>
        ) : (
          <ScrollArea type="hover" h="calc(100vh - 21rem)" scrollbarSize={6}>
            <Flex flexWrap="wrap" gap="2" w="full">
              {layerSrcList.map(({ src, color }, index) => (
                <Flex
                  key={color}
                  bg="blackAlpha.600"
                  w="full"
                  height="calc(1rem + 80px)"
                  align="center"
                  gap="4"
                  p="2"
                  rounded="base"
                >
                  <Icon
                    as={hideIndex[index] ? FaEye : FaEyeSlash}
                    boxSize={7}
                    cursor="pointer"
                    onClick={() => handleHideLayer(index)}
                  />
                  <Image
                    boxSize="80px"
                    src={src}
                    objectFit="contain"
                    userSelect="none"
                  />
                  <Flex flexGrow="1" flexDirection="column" h="full">
                    <Text fontWeight="bold" fontSize="xl" userSelect="none">
                      当前颜色值
                    </Text>
                    <Text>{`RGB(${color})`}</Text>
                  </Flex>
                </Flex>
              ))}
            </Flex>
          </ScrollArea>
        )}
      </Flex>
    </Flex>
  ) : null;
}
